<?php

namespace App\Jobs;

use App\Models\Goods;
use App\Models\SeckillGoods;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;

/**
 * 秒杀商品清理 延时队列
 * @package App\Jobs
 */
class KillGoodsClear implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    protected $seckill_id;

    public function __construct($seckill_id)
    {
        $this->seckill_id = $seckill_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        echo $this->seckill_id;

        $seckill = SeckillGoods::query()->where(['id'=>$this->seckill_id])->first();

//        if($seckill['kill_status'] != 1){
//            //结束队列
//            echo "---队列结束";
//            $this->delete();
//        }

        // 更新秒杀商品的状态  先判断该商品是否已经在秒杀状态
        \DB::beginTransaction();
        try {
            Goods::query()->where(['id'=>$seckill['goods_id']])->update(['kill_status'=>0]);
            SeckillGoods::query()->where(['id'=>$this->seckill_id])->update(['kill_status'=>0]);

            \DB::commit();
        }catch (\Exception $e){
            Log::info('秒杀更新商品状态失败：' . $e->getMessage());
            \DB::rollBack();
        }

    }
}
